package com.motu.monstercity.server.game.timedtask;

import com.motu.monstercity.server.game.base.AllParam;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

public class TimeTaskConfig extends TimeTaskConfigModel {

	public final static Logger logger = LoggerFactory.getLogger(TimeTaskConfig.class);

    public TimeTaskConfig(JsonObject obj) {
        super(obj);
    }

    /**
     * 获取下次执行时间
     */
    public long getNextTime() {
        long curTime = TimeUtils.getCurTime();
        try {
            // 计算执行时间
            String strTime;
            if (Tool.isNum(getTime())) {
                strTime = getTime() + ":00:00";
            } else {
                if (getTime().contains(":")) {
                    strTime = getTime();
                } else {
                    Class<AllParam> clazz = AllParam.class;
                    Field field = clazz.getField(getTime());
                    if (field.getType() == int.class) {
                        strTime = field.getInt(clazz) + ":00:00";
                    } else {
                        strTime = (String) field.get(clazz);
                    }
                }
            }
            // 计算执行周期
            String strWeek = "";
            if (!Tool.isEmpty(getWeek())) {
                if (Tool.isNum(getWeek())) {
                    strWeek = TimeUtils.getWeekOneDay(Integer.parseInt(getWeek()));
                } else {
                    Class<AllParam> clazz = AllParam.class;
                    Field field = clazz.getField(getWeek());
                    strWeek = TimeUtils.getWeekOneDay(field.getInt(clazz));
                }
            }
            long nextTime;
            if (Tool.isEmpty(getWeek())) {// 每日
                long diffTime = TimeUtils.dayDifftime(strTime, getOffset());
                if (diffTime <= 0) {
                    nextTime = curTime + TimeUtils.DAY;
                } else {
                    nextTime = curTime + diffTime;
                }
            } else {// 每周
                long diffTime = TimeUtils.weekDifftime(strWeek, strTime, getOffset());
                if (diffTime <= 0) {
                    nextTime = curTime + TimeUtils.WEEK;
                } else {
                    nextTime = curTime + diffTime;
                }
            }
            return nextTime;
        } catch (Exception e) {
            logger.error(Tool.getException(e));
            return Integer.MAX_VALUE;
        }
    }
}
